<?php
/**
 * Created by PhpStorm.
 * User: spatra
 * Date: 15-1-7
 * Time: 下午9:25
 */

use \Symfony\Component\HttpFoundation\File\UploadedFile as UploadedFile;

class LessonResourceController extends \BaseController
{
    /**
     * 获取课堂的资源列表.
     *
     * @param $lessonId
     * @return \Illuminate\Http\JsonResponse
     *
     * 返回的JSON格式如下：
     * {
     *  "privilege": {
     *      "delete": "是否有删除资源的权限，true或false",
     *      "upload": "是否有上传资源的权限，true或false",
     *   },
     *  "resources": [
     *      {
     *          "id": "资源id",
     *          "origin_name": "用户上传时的文件名",
     *          "ext_name": "文件扩展名",
     *          "real_name": "文件储存时的文件名",
     *          "creater_id": "创建者用户id",
     *          "creater": {
     *              "id": "用户id",
     *              "username": "用户名",
     *              "head_image": "用户头像"
     *          }
     *      },
     *      /注意是个数组....
     *   ]
     * }
     */
    public function index($lessonId)
    {
        $resp['privilege'] = $this->getPrivilegeDesc($lessonId);
        $resp['resources'] = Lesson_Resource::with('creater')
            ->where('lesson_id', $lessonId)
            ->get()->toArray();

        return Response::json($resp);
    }

    /**
     * 生成当前用户对资源列表的操作权限表述.
     *
     * @param $lessonId
     * @return array
     */
    protected function getPrivilegeDesc($lessonId)
    {
        $targetLesson = Lesson::findOrFail($lessonId);
        $currentUserId =  Auth::user()['id'];

        $privilege['delete'] = $currentUserId == $targetLesson['teacher_id'];

        $privilege['upload'] = $privilege['delete'] ||
            Lesson_Student::where('lesson_id', $lessonId)
                ->where('student_id', $currentUserId)
                ->first();

        return $privilege;
    }

    /**
     * 实现文件上传.
     *
     * 提交文件的字段为： file
     *
     * @param $lessonId
     * @return \Illuminate\Http\JsonResponse
     *
     * 返回的JSON格式：
     *  【成功时】:
     *      {
     *          "id": "资源id"
     *      }
     *  【失败时]
     *      {
     *          "error": "相关的错误信息"
     *      }
     */
    public function store($lessonId)
    {
        $privilege = $this->getPrivilegeDesc($lessonId);
        if( ! $privilege['upload'] ){
            return Response::json([
                'error'=>'没有上传资源的权限'
            ], 403);
        }

        $validator = $this->getUploadValidator(Input::all());

        if( $validator->passes() ){
            $file = Input::file('file');
            $newFilename = $this->getNewFilename($lessonId, $file);

            $file->move(Lesson_Resource::getResourceDirectory(), $newFilename);

            $add = Lesson_Resource::create([
                'origin_name'=>$file->getClientOriginalName(),
                'ext_name'=>$file->getClientOriginalExtension(),
                'mime'=>$file->getClientMimeType(),
                'real_name'=>$newFilename,
                'creater_id'=>Auth::user()['id'],
                'lesson_id'=>$lessonId,
                'from_teacher'=>$privilege['delete']
            ]);

            return Response::json([
                'id'=>$add['id']
            ]);

        }else{

            return Response::json([
                'error'=>$this->changeValidatorMessageToString($validator->getMessageBag())
            ], 403);
        }

    }

    /**
     * 得到新的文件名
     *
     * @param $lessonId 课程id
     * @param UploadedFile $file 文件对象
     * @return string
     */
    protected function getNewFilename($lessonId, UploadedFile $file)
    {
        return $lessonId.
            '-'.
            time().
            '.'.
            $file->getClientOriginalExtension();
    }

    /**
     * 校验文件格式的校验器.
     *
     * @param $postData
     * @return \Illuminate\Validation\Validator
     */
    protected function getUploadValidator($postData)
    {
        $rules = [
//            'file'=>'mimes:doc,docx,txt,xls,pdf,ppt,jpg,jpeg,png|max:5120'
            'file'=>'max:5120'
        ];

        return Validator::make($postData, $rules);

    }

    /**
     * 实现资源下载.
     *
     * @param $lessonId
     * @param $resourceId
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    public function show($lessonId, $resourceId)
    {
        $targetResource = Lesson_Resource::where('lesson_id', $lessonId)
            ->where('id', $resourceId)
            ->firstOrFail();
        $realFilePath = Lesson_Resource::getResourceRealPath($targetResource);

        return Response::download($realFilePath);
    }

    /**
     * 针对不同的浏览器，处理文件下载的头部信息
     *
     * @param $targetResource
     * @return mixed
     */
    protected function getFileDownloadBrowserHeader($targetResource)
    {
        $ua = Request::header('user-agent');

        $realFilePath = Lesson_Resource::getResourceRealPath($targetResource);
        $filename = $targetResource['origin_name'];
        $encoded_filename = rawurlencode($filename);

        if( preg_match("/MSIE/", $ua) ){
            $headers['Content-Disposition'] =  ' attachment; filename="' . $encoded_filename . '"';
        }else if( preg_match("/Firefox/", $ua) ){
            $headers['Content-Disposition'] = " attachment; filename*=\"utf8''" . $filename . '"';
        }else{
            $headers['Content-Disposition'] = ' attachment; filename="' . $filename . '"';
        }

        $headers['Content-Type'] = $targetResource['mime'];
        $headers['Content-Length'] = filesize($realFilePath);
//        $headers['Location'] = '/lesson_resource/'. $targetResource['real_name'];
        $headers['Accept-Ranges'] = 'bytes';
        $headers['Connection'] = 'Keep-Alive';

        return $headers;
    }

    /**
     * 删除文件.
     * 
     * @param $lessonId
     * @param $resourceId
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function destroy($lessonId, $resourceId)
    {
        $targetResource = Lesson_Resource::where('lesson_id', $lessonId)
            ->where('id', $resourceId)
            ->firstOrFail();

        $rightToDelete = $this->getPrivilegeDesc($lessonId)['delete'] || $targetResource['creater_id'];
        if( $rightToDelete
            && unlink( Lesson_Resource::getResourceRealPath($targetResource) )){

            $targetResource->delete();
            return Response::make('', 200);
        }else{
            return Response::json([
                'error'=>'删除文件失败'
            ], 403);
        }
    }

}